package handle

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/jhoncy/schelper/model"
	"net/http"
)

type rule struct {
	Name 		string 			`json:"name" binding:"required"`
}

type policy struct {
	Name 		string 			`json:"name" binding:"required"`
	RoleId  	uint 			`json:"roleId" binding:"required"`
	Policy		interface{} 	`json:"policy" binding:"required"`
}


//create a rule
func CreateRule(c *gin.Context) {
	req := rule{}
	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "bad request"})
		return
	}
	var unique model.CoreRole
	model.DB().Where("name = ?", req.Name).Select("name").First(&unique)
	if unique.Name != "" {
		c.JSON(http.StatusConflict, gin.H{"error": "this role name already exists"})
		return
	}
	model.DB().Create(&model.CoreRole{
		Name: req.Name,
	})
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}

//create a binding role policy
func CreatePolicy(c *gin.Context) {
	req := policy{}
	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "bad request"})
		return
	}
	jsonPolicy, err := json.Marshal(req.Policy)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "bad request"})
		return
	}
	var role model.CoreRole
	model.DB().Where("id = ?", req.RoleId).Select("name").First(&role)
	if role.Name == "" {
		c.JSON(http.StatusNotFound, gin.H{"error": "role does not exist"})
		return
	}
	var unique model.CoreRolePolicy
	model.DB().Where("name = ?", req.Name).Select("name").First(&unique)
	if unique.Name != "" {
		c.JSON(http.StatusConflict, gin.H{"error": "this policy name already exists"})
		return
	}
	model.DB().Create(&model.CoreRolePolicy{
		Name: req.Name,
		RoleID: req.RoleId,
		RoleName: role.Name,
		Policy: string(jsonPolicy),
	})
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}